<template>
  <a-layout style="height: 100vh">
    <a-layout-sider
      v-model:collapsed="collapsed"
      theme="light"
      collapsible
      style="border-right: 1px solid #e8e8e8"
    >
      <div class="logo">
        <img src="@/assets/vue.svg" alt="logo" />
        <!-- <h1 v-if="!collapsed">ERP System</h1> -->
      </div>
      <a-menu
        v-model:selectedKeys="state.selectedKeys"
        v-model:openKeys="state.openKeys"
        :inline-collapsed="state.collapsed"
        :items="items"
        mode="inline"
        @click="openPane"
      >
      </a-menu>
    </a-layout-sider>
    <a-layout>
      <a-layout-header style="background: #fff; padding: 0 30px">
        <a-flex justify="end" align="center">
          <!-- <a-space>
            <SyncOutlined
              style="cursor: pointer; font-size: 18px; color: #999"
              @click="refresh"
            />
            
          </a-space> -->

          <a-dropdown>
            <a class="ant-dropdown-link" @click.prevent>
              <span style="padding-right: 10px;">{{userInfo.nickname}}</span>

              <a-avatar src="">
                <template #icon>
                  <UserOutlined />
                </template>
              </a-avatar>
            </a>
            <template #overlay>
              <a-menu>
                <a-menu-item>
                  <a href="javascript:;"> 个人中心 </a>
                </a-menu-item>
                <a-menu-item>
                  <a href="javascript:;">退出登录</a>
                </a-menu-item>
              </a-menu>
            </template>
          </a-dropdown>
        </a-flex>
      </a-layout-header>
      <a-layout-content class="body-content">
        <!-- 打开的页面的tabs -->
        <a-tabs class="a-tabs-card"
          v-model:activeKey="activeKey"
          hide-add
          type="editable-card"
          @edit="closePane"
          @change="changePane"
        >
          <a-tab-pane
            v-for="pane in panes"
            :key="pane.key"
            :tab="pane.title"
            :closable="pane.closable"
          >
            <div class="pane-content">
                <component :is="pane.component" />
            </div>
            <!-- <async-component-wrapper :component="pane.component" /> -->
          </a-tab-pane>
        </a-tabs>
      </a-layout-content>
      <a-layout-footer style="text-align: center">
        ERP管理系统 © 2025 Created by Usha
      </a-layout-footer>
    </a-layout>
  </a-layout>
</template>

<script setup>
// import AsyncComponentWrapper from '@/components/AsyncComponentWrapper.vue';
import { ref, reactive, h, shallowRef,defineAsyncComponent,onMounted } from "vue";
import { useRouter } from "vue-router";
const router = useRouter();
import { message } from 'ant-design-vue';
import * as Icons from '@ant-design/icons-vue';
import {
  UserOutlined,
  HomeOutlined,
  SettingOutlined,
  SyncOutlined,
} from "@ant-design/icons-vue";
import api from "@/api"
import { useUserStore } from "@/store";
const userStore = useUserStore();
const collapsed = ref(false);
const state = reactive({
  selectedKeys: ["home"],
  openKeys: ["home"],
  collapsed: false,
});
const items = ref([])
const items_default = reactive([
  {
    key: "home",
    label: "欢迎页",
    title: "欢迎页",
    icon: h(HomeOutlined),
  },
  
]);
const userInfo = ref({})
userInfo.value = userStore.getUserInfo()
console.log(userInfo.value)
const activeKey = ref("");
const panes = ref([]);

// 打开新的页面

const openPane = (item) => {
  const title = item.item.originItemValue.label;
  const {key,keyPath } = item
  const index = panes.value.findIndex((pane) => pane.key === key);
  if (index !== -1) {
    activeKey.value = key;
    return;
  }

  // 查找对应路由的组件
  const route = router.getRoutes().find((r) => r.name === key);

  if (route) {
    // 处理动态导入的组件
    const component =
      typeof route.components.default === "function" &&
      !route.components.default.prototype
        ? defineAsyncComponent(route.components.default) // 包装动态导入的组件
        : route.components.default;
    panes.value.push({
      key,
      keyPath,
      title: title,
      closable: true,
      component: shallowRef(component),
    });
    activeKey.value = key;
  } else {
    console.warn(`未找到名称为 ${key} 的路由`);
    // 可以添加用户提示
    message.warning(`未找到名称为 ${key} 的路由`);
  }
};
// 关闭页面
const closePane = (key) => {
  const index = panes.value.findIndex((pane) => pane.key === key);
  if (index !== -1) {
    panes.value.splice(index, 1);
    activeKey.value = panes.value[0].key;
    state.openKeys = [panes.value[0]?.keyPath[0]];
    state.selectedKeys = panes.value[0]?.keyPath;
  }
};

// 页面切换
const changePane = (key) => {
  const index = panes.value.findIndex((pane) => pane.key === key);
  if (index !== -1){
    activeKey.value = key;
    state.openKeys = [panes.value[index]?.keyPath[0]];
    state.selectedKeys = panes.value[index]?.keyPath;
  }
};

// 页面刷新
const refreshPane = (key) => {
  console.log(key);
};

// 刷新页面
const refresh = () => {
  window.location.reload();
};
const init = async ()=> {
  const menus = await api.getRoleMenus()
  if(!menus.length) return
  const newMenus = menus.map(item=>{
    const hasChildren = item.children && item.children.length > 0
    const child = {}    
    
    // 获取当前菜单项对应的图标组件
    const IconComponent = Icons[item.icon] || '';
    
    if(hasChildren){
      child.children = item.children.map(childItem=>{
        // 获取子菜单项对应的图标组件
        const ChildIconComponent = Icons[childItem.icon] || '';
        return {
          key: childItem.key,
          label: childItem.title,
          icon: item.icon!==''?h(ChildIconComponent):'',

        }
      })
    }
    
    const obj = {
      key: item.key,
      label: item.title,
      icon: item.icon!==''?h(IconComponent):'',
      ...child
    } 
    return obj
  })
  items.value = newMenus 
  const firstMenu = menus.filter(item=>item.key === 'home')[0]
  activeKey.value = firstMenu.key
  const onePane = {
    ...firstMenu,
    icon: h(firstMenu.icon),
    keyPath: [firstMenu.key],
    label:firstMenu.title,
    closable: false,
    component: shallowRef(
      router.getRoutes().find((r) => r.name === firstMenu.key)?.components.default
    ),
  }
  panes.value = [onePane]
}
onMounted(()=>{
  init()
})


</script>

<style lang="scss" scoped>
.logo {
  padding: 10px 15px;
  display: flex;
  flex-wrap: nowrap;
  justify-content: center;
  align-items: center;
}
::v-deep(.a-tabs-card){
    .ant-tabs-nav{
        margin-bottom: 0;
    }
    .ant-tabs-tab{
        border: 0;
        border-radius: 0!important;
    }
    .ant-tabs-tab-active{
        background: #e6f4ff;
    }
}
.body-content{
  width: 100%;
  height: 100%;
  overflow: hidden;
  border-top: #e8e8e8 1px solid;
  background-color: #fff;
  overflow-y: auto;
}
</style>
